package com.lant.web.interceptor;

import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import com.lant.enums.ResponseStatusEnum;
import com.lant.pojo.LantResult;
import com.lant.pojo.LantUser;
import com.lant.service.LantUserService;
import com.lant.utils.CookieUtils;
import com.lant.utils.ObjectUtils;
import com.lant.web.constant.FieldConstant;
import com.lant.web.constant.UrlConstant;

/**
 * @description: 登录拦截器
 * @projectName: lant-manager-web
 * @className: LoginHandlerInterceptor
 * @author: YFL
 * @createTime: 2020年5月6日 上午10:36:48
 */
public class LoginHandlerInterceptor implements HandlerInterceptor {

    private static final Logger logger = LoggerFactory.getLogger(LoginHandlerInterceptor.class);

    @Autowired
    private LantUserService lantUserService;
    // 设置不检查的URL
    private Set<String> inherentEscapeURIS;

    public void setInherentEscapeURIS(Set<String> inherentEscapeURIS) {
        this.inherentEscapeURIS = inherentEscapeURIS;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
        throws Exception {
        // // 获取请求URL
        String requestUrl = request.getRequestURI();
        // 判断是否不过滤的请求
        if (inherentEscapeURIS.contains(requestUrl)) {
            return true;
        }

        // 在Handler执行之前处理
        // 判断用户是否登录
        // 从cookie中取token
        String token = CookieUtils.getCookieValue(request, FieldConstant.getLantToken());

        if (ObjectUtils.isEmpty(token)) {
            // 跳转到登录页面，把用户请求的url作为参数传递给登录页面。
            // 这是为了登录以后跳转到之前的操作页面方便用户体验
            response.sendRedirect(UrlConstant.PAGE_LOGIN_URL);
            // 返回false
            return false;
        }

        LantResult result = lantUserService.getUserByToken(token);
        if (result.getStatus().equals(ResponseStatusEnum.BAD_REQUEST.getValue())) {
            logger.error(String.format("查询用户信息异常", result.getMsg()));
            response.sendRedirect(UrlConstant.PAGE_LOGIN_URL);
            // 返回false
            return false;
        }

        LantUser user = (LantUser) result.getData();

        // 取不到用户信息
        if (ObjectUtils.isNull(user)) {
            // 跳转到登录页面，把用户请求的url作为参数传递给登录页面。
            // 这是为了登录以后跳转到之前的操作页面方便用户体验
            response.sendRedirect(UrlConstant.PAGE_LOGIN_URL);
            // 返回false
            return false;
        }

        // 取到用户信息，放行
        // 将user对象放入request
        request.setAttribute("user", user);
        // 返回值决定handler是否执行。true：执行，false：不执行。
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
        ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
        throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
